package com.linkage.educloud.ah.view.activity.app;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.linkage.educloud.ah.R;
import com.linkage.educloud.ah.adapter.AppDetailChargesAdapter;
import com.linkage.educloud.ah.bean.AccountData;
import com.linkage.educloud.ah.bean.AppDetail;
import com.linkage.educloud.ah.bean.PicItem;
import com.linkage.educloud.ah.config.AccountConfig;
import com.linkage.educloud.ah.mvp.contract.IAppDetailContract;
import com.linkage.educloud.ah.mvp.presenter.AppDetailPresenter;
import com.linkage.educloud.ah.util.ImageLoader;
import com.linkage.educloud.ah.view.BasicTitleActivity;
import com.linkage.educloud.ah.view.activity.big_picture.BigPictureActivity;
import com.linkage.educloud.ah.widget.CommonDialog;
import com.linkage.educloud.ah.widget.NoScrollListView;
import com.zzhou.common.library.util.ToastShow;
import com.zzhou.common.library.util.Utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * Created by Mr'Tang on 2018/12/20.
 */

public class AppDetailActivity extends BasicTitleActivity implements View.OnClickListener, IAppDetailContract.IView {

    @BindView(R.id.ac_app_detail_icon)
    ImageView ac_app_detail_icon;
    @BindView(R.id.ac_app_detail_name_price)
    TextView ac_app_detail_name_price;
    @BindView(R.id.ac_app_detail_provider)
    TextView ac_app_detail_provider;
    @BindView(R.id.ac_app_detail_usenum)
    TextView ac_app_detail_usenum;
    @BindView(R.id.ac_app_detail_expiretime)
    TextView ac_app_detail_expiretime;
    @BindView(R.id.ac_app_detail_charges)
    NoScrollListView ac_app_detail_charges;
    @BindView(R.id.line_charges)
    View line_charges;
    @BindView(R.id.ac_app_detail_preview)
    LinearLayout ac_app_detail_preview;
    @BindView(R.id.ac_app_detail_desc)
    TextView ac_app_detail_desc;
    @BindView(R.id.ac_app_detail_help)
    TextView ac_app_detail_help;
    @BindView(R.id.ac_app_detail_useforfree)
    Button ac_app_detail_useforfree;
    @BindView(R.id.ac_app_detail_buynow)
    Button ac_app_detail_buynow;

    private static final String KEY_ID = "id";
    private AppDetail appDetail;
    IAppDetailContract.IPresenter iPresenter;
    AccountData accountData;

    public static void launch(Context context, String id) {
        Intent intent = new Intent(context, AppDetailActivity.class);
        intent.putExtra(KEY_ID, id);
        context.startActivity(intent);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_app_detail;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        accountData = AccountConfig.getLoginAccount();
        iPresenter = new AppDetailPresenter(this, this);
        showZloading();
        iPresenter.getAppDetails(getIntent().getStringExtra(KEY_ID));
        ac_app_detail_help.setOnClickListener(this);
        ac_app_detail_useforfree.setOnClickListener(this);
        ac_app_detail_buynow.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ac_app_detail_help:
                ToastShow.show(this, "使用帮助" + appDetail.getHelp_url());
                break;
            case R.id.ac_app_detail_useforfree:
                click_useforfree();
                break;
            case R.id.ac_app_detail_buynow:
                click_buynow();
                break;
        }
    }

    private void click_useforfree() {
        iPresenter.statisticsData(appDetail.getId());//我也不懂为啥这边点击就请求 和这个接口的标注不符
        if (accountData == null) {
            ToastShow.show(AppDetailActivity.this, R.string.tips_unregister);
            return;
        }
        if (appDetail.getOrder_mode() == 1) {
            if (!appDetail.getInvalid_time().isEmpty()) {
                ToastShow.show(this, "to webview");
            } else {
                final CommonDialog mDialog = new CommonDialog(AppDetailActivity.this, "提示消息", "确定要退订该应用吗？", "取消", "确定");
                mDialog.setCancelListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mDialog.isShowing()) {
                            mDialog.dismiss();
                        }
                    }
                });
                mDialog.setOkListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mDialog.isShowing()) {
                            fetchAuthData();
                            mDialog.dismiss();
                        }
                    }
                });
                mDialog.show();
            }
        }
        if (appDetail.getInapp_mode() == 1 && appDetail.getOrder_mode() == 2) {
            if (appDetail.getType() == 4) {
                final CommonDialog mDialog = new CommonDialog(AppDetailActivity.this, "温馨提示", "该产品仅限网站端使用，请登录和教育网站(www.anhuiwx.cn)进入资源中心下载使用。", "", "知道了");
                mDialog.setOkListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mDialog.isShowing()) {
                            mDialog.dismiss();
                        }
                    }
                });
                mDialog.show();
            } else {
                iPresenter.getAppDetails(getIntent().getStringExtra(KEY_ID));
                ToastShow.show(this, "to webview");
            }

        }
        if (appDetail.getInapp_mode() == 2 && appDetail.getOrder_mode() == 2) {
            if (!appDetail.getUrl().isEmpty()) {
                iPresenter.getAppDetails(getIntent().getStringExtra(KEY_ID));
                ToastShow.show(this, "to webview");
            } else {
                final CommonDialog mDialog = new CommonDialog(AppDetailActivity.this, "温馨提示", "该产品仅限网站端使用，请登录和教育网站(www.anhuiwx.cn)进入资源中心下载使用。", "", "知道了");
                mDialog.setOkListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mDialog.isShowing()) {
                            mDialog.dismiss();
                        }
                    }
                });
                mDialog.show();
            }
        }
    }

    private void click_buynow() {
        if (accountData == null) {
            ToastShow.show(AppDetailActivity.this, R.string.tips_unregister);
            return;
        }
        if (accountData.getUserType() == 1 && "互动课堂".equals(appDetail.getName())) {
            final CommonDialog dialog = new CommonDialog(AppDetailActivity.this, "温馨提示",
                    "该产品仅限网站端使用，请登录智慧校园网站进行下载使用。", "", "知道了");
            dialog.setOkListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dialog.isShowing()) {
                        dialog.dismiss();
                    }
                }
            });
            dialog.show();
        } else if (appDetail.getOrder_mode() == 2 && appDetail.getSource_id() == 3) {//讲道理，我也不知道source_id==3是啥东西
            if (appDetail.getType() == 3) {
                ToastShow.show(this, "to 合肥一中");
            } else {
                ToastShow.show(this, "to webview");
            }
        } else if (appDetail.getOrder_mode() == 2) {
            if (appDetail.getInapp_mode() == 0) {
                ToastShow.show(this, "to webview");
            } else {
                if (appDetail.getSource_id() == 1) {
                    AppAuthActivity.launch(this, appDetail, null);
                } else {
                    ToastShow.show(this, "to webview");
                }
            }
        } else {
            if (appDetail.getType() == 1) {//进第三方app
                if (Utils.checkApkExist(AppDetailActivity.this, appDetail.getLauncher_path())) {
                    Map<String, Object> params = new HashMap<String, Object>();
                    if (TextUtils.isEmpty(appDetail.getUrl())) {
                        Utils.runAppByParam(AppDetailActivity.this, appDetail.getLauncher_path(), params);
                    } else {
                        Utils.runAppByParam(AppDetailActivity.this, appDetail.getLauncher_path(), appDetail.getUrl(), params);
                    }
                } else {
                    if (!appDetail.getUrl().isEmpty()) {
                        AppDetailActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(appDetail.getUrl())));
                    } else {
                        ToastShow.show(AppDetailActivity.this, "应用下载地址为空");
                    }
                }
            } else {//进H5
                if (appDetail.getType() == 4) {
                    final CommonDialog mDialog = new CommonDialog(
                            AppDetailActivity.this,
                            "温馨提示",
                            "该产品仅限网站端使用，请登录和教育网站（www.anhuiwx.cn)进入资源中心下载使用。",
                            "", "知道了");
                    mDialog.setOkListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mDialog.isShowing()) {
                                mDialog.dismiss();
                            }
                        }
                    });
                    mDialog.show();
                } else {
                    ToastShow.show(this, "to webview");
                }
            }
        }
    }

    public void initDate(final List<AppDetail> list) {
        hideZloading();
        appDetail = list.get(0);//无论如何先显示第一种价格
        int num = 0;
        if (list.size() > 1) {
            for (int i = 0; i < list.size(); i++) {
                num = num + list.get(i).getOrder_num();
            }
            ac_app_detail_charges.setVisibility(View.VISIBLE);
            line_charges.setVisibility(View.VISIBLE);
            final AppDetailChargesAdapter appDetailChargesAdapter = new AppDetailChargesAdapter(this, list);
            ac_app_detail_charges.setAdapter(appDetailChargesAdapter);
            ac_app_detail_charges.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    appDetailChargesAdapter.update(position);
                    appDetail = list.get(position);
                    initOneDate();
                }
            });
        } else {
            num = appDetail.getOrder_num();
        }
        ac_app_detail_usenum.setText(Html.fromHtml("<font color='#7bc228'>" + num + "</font>" + "人在用"));
        initOneDate();
    }

    private void initOneDate() {
        ImageLoader.loadAvatar(this, appDetail.getLogo(), ac_app_detail_icon);
        loadImg(appDetail.getIntro_imgs());
        if (!appDetail.getInvalid_time().isEmpty() && appDetail.getSource_id() != 1) {
            ac_app_detail_expiretime.setVisibility(View.VISIBLE);
            ac_app_detail_expiretime.setText(appDetail.getInvalid_time() + "使用到期");
        }
        ac_app_detail_provider.setText(appDetail.getAuthor());
        ac_app_detail_desc.setText(appDetail.getIntroduction());
        if (appDetail.getSource_id() == 1) {
            ac_app_detail_help.setVisibility(View.VISIBLE);
        }
        if (appDetail.getInapp_mode() == 0) {//免费
            if (appDetail.getType() == 3) {
                ac_app_detail_name_price.setText(appDetail.getName());
            } else {
                ac_app_detail_name_price.setText(appDetail.getName());
                Drawable drawable = getResources().getDrawable(R.mipmap.ic_free);
                drawable.setBounds(0, 0, 35, 35);
                ac_app_detail_name_price.setCompoundDrawables(null, null, drawable, null);
            }
            ac_app_detail_buynow.setText("进入使用");
        } else {//1--单资费 2--多资费
            ac_app_detail_usenum.setVisibility(View.VISIBLE);
            ac_app_detail_name_price.setText(Html.fromHtml(appDetail.getName() + "&emsp&emsp&emsp" + "<font color='#7bc228'>" + appDetail.getPrice() + "元/月" + "</font>"));
            if (appDetail.getOrder_mode() == 1) {
                if (!appDetail.getInvalid_time().isEmpty() && appDetail.getSource_id() != 1) {
                    ac_app_detail_useforfree.setBackgroundResource(R.mipmap.bg_orange);
                    ac_app_detail_useforfree.setText("续订");
                } else {
                    ac_app_detail_useforfree.setBackgroundResource(R.mipmap.bg_green);
                    ac_app_detail_useforfree.setText("退订应用");
                }
                ac_app_detail_buynow.setText("进入使用");
                ac_app_detail_useforfree.setVisibility(View.VISIBLE);
            } else {
                ac_app_detail_useforfree.setBackgroundResource(R.mipmap.bg_orange);
                ac_app_detail_useforfree.setText("免费试用");
                ac_app_detail_buynow.setText("现在订购");
                ac_app_detail_useforfree.setVisibility(View.VISIBLE);
            }
        }
    }

    private void loadImg(String img_url) {
        final String[] pic_list = img_url.split(",");
        for (int i = 0; i < pic_list.length; i++) {
            final int a = i;
            View itemView = LayoutInflater.from(AppDetailActivity.this).inflate(
                    R.layout.item_app_detail_preview, null);
            ImageView imageView = itemView.findViewById(R.id.item_preview_img);
            ImageLoader.loadImg(this, pic_list[i], imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ArrayList<PicItem> picItems = new ArrayList<>();
                    for (int a = 0; a < pic_list.length; a++) {
                        PicItem picItem = new PicItem(pic_list[a], a);
                        picItems.add(picItem);
                    }
                    BigPictureActivity.launch(AppDetailActivity.this, picItems, a);
                }
            });
            ac_app_detail_preview.addView(itemView);
        }
    }

    //退订逻辑
    private void fetchAuthData() {
        if (!appDetail.getInvalid_time().isEmpty()) {
            ToastShow.show(this, "to webview");
        } else {
            iPresenter.companyAppGrantNew(appDetail.getId(), "", 2, appDetail.getServiceId());
        }
    }

    public void update(){
        iPresenter.getAppDetails(getIntent().getStringExtra(KEY_ID));
    }
}
